<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <h1 id="show">距离下课还有</h1>

    <script>

        var oH1 =document.getElementById('show') ;

        var res = djs(new Date('2022-3-4 18:0:0') , new Date()) ;

        var gap ;    // 声明为全局变量

        oH1.innerHTML = '距离下课还有' + res;


        var t = setInterval(function(){

            var res = djs(new Date('2022-3-4 18:0:0') , new Date()) ;

            oH1.innerHTML = '距离下课还有' + res;

            // 时间差为0，表示时间到了   gap访问不到(他是局部变量)
            if(gap <= 0) {
                alert('下课了') ;
                clearInterval(t) ;
                oH1.innerHTML = '时间到期了' ;
            }
            
        } , 1000)



        function djs(t1 , t2) {  

            var future = new Date(t1) ;

            var now = new Date(t2) ;

            gap = parseInt((future - now) / 1000) ; 

            var h = parseInt(gap / 3600) ;

            var m = parseInt(gap % 3600 / 60) ;

            var s = gap % 60 ;

            return h + ':' + m + ':' + s
        }



    </script>
    
</body>
</html>